# -*- coding: utf-8 -*-


from ctypes import *

import win32api
import wx
import wx.xrc
import wx.adv
from ctypes import *
import pythoncom
import PyHook3

from mythread import MyThread

m_times = 6


class MyFrame1(wx.Frame):

    def __init__(self, parent):
        wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=wx.EmptyString, pos=wx.DefaultPosition,
                          size=wx.Size(500, 300), style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL)

        self.SetSizeHints(wx.DefaultSize, wx.DefaultSize)

        bSizer1 = wx.BoxSizer(wx.VERTICAL)

        gbSizer1 = wx.GridBagSizer(0, 0)
        gbSizer1.SetFlexibleDirection(wx.BOTH)
        gbSizer1.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)

        m_choice2Choices = [u"1", u"2", u"3", u"4", u"5", u"10", u"15", u"20", u"25", u"30", u"60", wx.EmptyString]
        self.m_choice2 = wx.Choice(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, m_choice2Choices, 0)
        self.m_choice2.SetSelection(0)
        gbSizer1.Add(self.m_choice2, wx.GBPosition(0, 0), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_toggleBtn2 = wx.ToggleButton(self, wx.ID_ANY, u"开始", wx.DefaultPosition, wx.DefaultSize, 0)
        self.m_toggleBtn2.SetValue(True)
        gbSizer1.Add(self.m_toggleBtn2, wx.GBPosition(0, 1), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_toggleBtn3 = wx.ToggleButton(self, wx.ID_ANY, u"停止", wx.DefaultPosition, wx.DefaultSize, 0)
        gbSizer1.Add(self.m_toggleBtn3, wx.GBPosition(0, 2), wx.GBSpan(1, 1), wx.ALL, 5)

        self.btn_hides = wx.ToggleButton(self, wx.ID_ANY, u"隐藏", wx.DefaultPosition, wx.DefaultSize, 0)
        gbSizer1.Add(self.btn_hides, wx.GBPosition(0, 3), wx.GBSpan(1, 1), wx.ALL, 5)

        bSizer1.Add(gbSizer1, 1, wx.EXPAND, 5)

        self.SetSizer(bSizer1)
        self.Layout()
        self.m_timer1 = wx.Timer()
        self.m_timer1.SetOwner(self, wx.ID_ANY)
        self.m_timer1.Start(m_times * 1000)
        self.timer()

        self.Centre(wx.BOTH)

        # Connect Events
        self.Bind(wx.EVT_CLOSE, self.close)
        self.Bind(wx.EVT_TIMER, self.sleep, id=wx.ID_ANY)
        self.m_toggleBtn2.Bind(wx.EVT_TOGGLEBUTTON, self.start)
        self.m_toggleBtn3.Bind(wx.EVT_TOGGLEBUTTON, self.stop)
        self.btn_hides.Bind(wx.EVT_TOGGLEBUTTON, self.hides)

    def close(self, event):
        event.Skip()
        win32api.PostQuitMessage()
        print("PostQuitMessage")
        wx.Exit()

    def __del__(self):
        pass

    # Virtual event handlers, overide them in your derived class
    def timer(self):
        thread = MyThread(self)
        thread.start()

    def start(self, event):
        event.Skip()
        print("start")
        # self.timer()
        global m_times
        m_time = self.m_choice2.GetString(self.m_choice2.GetSelection())
        m_times = int(m_time) * 60
        print(m_times)
        self.m_timer1.Start(m_times * 1000)

    def stop(self, event):
        event.Skip()
        print("stop")
        self.m_timer1.Stop()
        win32api.PostQuitMessage()
        print("PostQuitMessage")

    def hides(self, event):
        event.Skip()
        self.Show(False)
        print("hides")

    def sleep(self, event):
        """关闭屏幕"""

        print("sleep")
        HWND_BROADCAST = 0xffff
        WM_SYSCOMMAND = 0x0112
        SC_MONITORPOWER = 0xF170
        MonitorPowerOff = 2
        SW_SHOW = 5

        windll.user32.PostMessageW(HWND_BROADCAST, WM_SYSCOMMAND,
                                   SC_MONITORPOWER, MonitorPowerOff)

        shell32 = windll.LoadLibrary("shell32.dll")
        shell32.ShellExecuteW(None, 'open', 'rundll32.exe',
                              'USER32,LockWorkStation', '', SW_SHOW)

    def onMouseEvent(self, event):
        # 监听鼠标事件
        if self.m_timer1.IsRunning():
            self.m_timer1.Start(m_times * 1000)
        global count, statue
        count = 0
        statue = True

        # print "MessageName:", event.MessageName
        # print "Message:", event.Message
        # print "Time:", event.Time
        # print "Window:", event.Window
        # print "WindowName:", event.WindowName
        # print "Position:", event.Position
        # print "Wheel:", event.Wheel
        # print "Injected:", event.Injected
        # print "---"

        # 返回 True 以便将事件传给其它处理程序
        # 注意，这儿如果返回 False ，则鼠标事件将被全部拦截
        # 也就是说你的鼠标看起来会僵在那儿，似乎失去响应了
        return True

    def onKeyboardEvent(self, event):
        # 监听键盘事件
        print(m_times * 1000)
        if self.m_timer1.IsRunning():
            self.m_timer1.Start(m_times * 1000)
        global count, statue
        count = 0
        statue = True

        # print "MessageName:", event.MessageName
        # print "Message:", event.Message
        # print "Time:", event.Time
        # print "Window:", event.Window
        # print "WindowName:", event.WindowName
        # print "Ascii:", event.Ascii, chr(event.Ascii)
        # print "Key:", event.Key
        # if event.Key == 'X':
        #     print "Key:", event.Key
        #     main_sleep()
        # print "KeyID:", event.KeyID
        # print "ScanCode:", event.ScanCode
        # print "Extended:", event.Extended
        # print "Injected:", event.Injected
        # print "Alt", event.Alt
        # print "Transition", event.Transition
        # print "---"

        # 同鼠标事件监听函数的返回值
        return True

    def hook(self):
        """钩子函数"""

        print("hook")
        # 创建一个“钩子”管理对象
        hm = PyHook3.HookManager()

        # 监听所有键盘事件
        hm.KeyDown = self.onKeyboardEvent
        # 设置键盘“钩子”
        hm.HookKeyboard()

        # 监听所有鼠标事件
        hm.MouseAll = self.onMouseEvent
        # 设置鼠标“钩子”
        hm.HookMouse()
        #
        # 进入循环，如不手动关闭，程序将一直处于监听状态
        pythoncom.PumpMessages()


class MyTaskBarIcon(wx.adv.TaskBarIcon):
    def __init__(self):
        wx.adv.TaskBarIcon.__init__(self)

        self.ICON = "wxpdemo.ico"  # 图标地址
        self.ID_ABOUT = wx.NewIdRef()  # 菜单选项“关于”的ID
        self.ID_EXIT = wx.NewIdRef()  # 菜单选项“退出”的ID
        self.ID_SHOW_WEB = wx.NewIdRef()  # 菜单选项“显示页面”的ID
        self.TITLE = "定时关闭屏幕"  # 鼠标移动到图标上显示的文字

        self.SetIcon(wx.Icon(self.ICON), self.TITLE)  # 设置图标和标题
        self.Bind(wx.EVT_MENU, self.about, id=self.ID_ABOUT)  # 绑定“关于”选项的点击事件
        self.Bind(wx.EVT_MENU, self.close, id=self.ID_EXIT)  # 绑定“退出”选项的点击事件
        self.Bind(wx.EVT_MENU, self.show, id=self.ID_SHOW_WEB)  # 绑定“显示页面”选项的点击事件

    # “关于”选项的事件处理器
    def about(self, event):
        wx.MessageBox('程序作者：David\n最后更新日期：2021-10-13', "关于")

    # “退出”选项的事件处理器
    def close(self, event):
        win32api.PostQuitMessage()
        wx.Exit()

    # “显示页面”选项的事件处理器
    def show(self, event):
        frame.Show(True)

    # 创建菜单选项
    def CreatePopupMenu(self):
        menu = wx.Menu()
        for mentAttr in self.menu():
            menu.Append(mentAttr[1], mentAttr[0])
        return menu

    # 获取菜单的属性元组
    def menu(self):
        return [('显示主界面', self.ID_SHOW_WEB),
                ('关于', self.ID_ABOUT),
                ('退出', self.ID_EXIT)]


if __name__ == "__main__":
    app = wx.App(False)
    frame = MyFrame1(None)
    frame.Show(True)
    MyTaskBarIcon()
    app.MainLoop()
    print("end applications")
